package com.atguigu.spzx.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.user.UserInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class SpzxUserInfoInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal();
    @Resource
    StringRedisTemplate stringRedisTemplate;
    //将token对应的用户对象绑定到线程对象的Map中 传递到线程经过的方法内使用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String userInfoKey = "user:login:"+ token;
        String userInfoJson = stringRedisTemplate.opsForValue().get(userInfoKey);
        UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
        THREAD_LOCAL.set(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       THREAD_LOCAL.remove();
    }
}
